<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>“随便乱画”画板</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div id="container">
      <h5>这是一个画板，你可以随便画画</h5>
      <canvas id="canvas" width="100" height="100"> </canvas>
    </div>

    <script>
      let canvas = document.getElementById("canvas");
      canvas.width = document.documentElement.clientWidth;
      canvas.height = document.documentElement.clientHeight;
      let ctx = canvas.getContext("2d");
      ctx.fillStyle = "black";
      ctx.strokeStyle = "none";
      ctx.lineWidth = 5;
      ctx.lineCap = "round";

      let painting = false;
      let last;

      //判断是否是触屏设备
      var isTouchDevice = "ontouchstart" in document.documentElement;
      if (isTouchDevice) {
        canvas.ontouchstart = (e) => {
          let x = e.touches[0].clientX;
          let y = e.touches[0].clientY;
          last = [x, y];
        };
        canvas.ontouchmove = (e) => {
          let x = e.touches[0].clientX;
          let y = e.touches[0].clientY;
          drawLine(last[0], last[1], x, y);
          last = [x, y];
        };
      } else {
        canvas.onmousedown = (e) => {
          painting = true;
          last = [e.clientX, e.clientY];
        };
        canvas.onmouseup = () => {
          painting = false;
        };

        canvas.onmousemove = (e) => {
          if (painting === true) {
            drawLine(last[0], last[1], e.clientX, e.clientY);
            last = [e.clientX, e.clientY];
          }
        };
      }
      function drawLine(x1, y1, x2, y2) {
        ctx.beginPath();
        ctx.moveTo(x1, y1);
        ctx.lineTo(x2, y2);
        ctx.stroke();
      }
    </script>
    <!--<script>
      canvas.onmousemove = (e) => {
        console.log(e.clientX);
        console.log(e.clientY);
        let div = document.createElement("div");
        div.style.position = "absolute";
        div.style.left = e.clientX + "px";
        div.style.top = e.clientY + "px";
        // div.style.border = "1px solid red";
        div.style.width = "6px";
        div.style.height = "6px";
        div.style.marginLeft = "-3px";
        div.style.marginTop = "-3px";
        div.style.borderRadius = "50%";
        div.style.background = "black";
        // 以上代码再内存里，不在页面里
        canvas.appendChild(div);
        // 添加一个孩子到canvas,现实再页面上了
      };
    </script> -->
  </body>
</html>
